package com.szboanda.platform.rms.dept.service.impl;

import com.szboanda.component.log.bizlog.BizLog;
import com.szboanda.component.log.bizlog.model.BizOperationLogVO;
import com.szboanda.platform.common.base.BaseService;
import com.szboanda.platform.common.component.datarecord.model.OperationType;
import com.szboanda.platform.common.component.datarecord.service.IDataRecordService;
import com.szboanda.platform.common.component.excel.service.IExcelService;
import com.szboanda.platform.common.component.tree.service.ITree;
import com.szboanda.platform.common.utils.*;
import com.szboanda.platform.rms.dept.cache.DeptCache;
import com.szboanda.platform.rms.dept.dao.DeptDAO;
import com.szboanda.platform.rms.dept.exception.DeptException;
import com.szboanda.platform.rms.dept.mode.DepartmentVO;
import com.szboanda.platform.rms.dept.service.IDeptService;
import com.szboanda.platform.rms.dept.utils.DeptUtil;
import com.szboanda.platform.rms.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 袁云飞
 * @create: 2020-12-16 21:00
 **/
@Service("DeptServiceImpl")
public class DeptServiceImpl extends BaseService implements IDeptService, ITree<DepartmentVO>, IExcelService {
    private static final String MODULE_NAME = "powerdata.platform.dept";
    private static final String TABLE_NAME = "T_ADMIN_RMS_ZZJG";
    @Autowired
    private DeptCache cache;
    @Autowired
    private DeptDAO deptDao;
    @Autowired
    private IUserService userService;
    @Resource(
            name = "DeptNoticeServiceImpl"
    )
    private DeptNoticeServiceImpl noticeService;
    @Autowired
    private IDataRecordService dataRecordService;
    private Map<String, Object> params;
    private Map<String, Object> param;

    public DeptServiceImpl() {
    }

    @Override
    public List<Map<String, Object>> getAllDept() throws DeptException {
        try {
            List<Map<String, Object>> deptList = this.cache.getAll();
            if (CollectionUtils.isEmpty(deptList)) {
                deptList = this.deptDao.findDept((Map)null);
                Iterator var2 = deptList.iterator();

                while(var2.hasNext()) {
                    Map<String, Object> dept = (Map)var2.next();
                    this.cache.saveCache(dept);
                }
            }

            return deptList;
        } catch (Exception var4) {
            LoggerUtil.error(this.getClass(), "获取所有部门异常", var4);
            throw new DeptException("获取所有部门异常", var4);
        }
    }

    @Override
    public Map<String, Object> getDeptByXh(String xh) throws DeptException {
        try {
            Map<String, Object> dept = this.cache.getCache(xh);
            if (CollectionUtils.isEmpty(dept)) {
                dept = this.deptDao.getDeptByXh(xh);
            }

            return dept;
        } catch (Exception var3) {
            LoggerUtil.error(this.getClass(), "获取部门失败：" + xh, var3);
            throw new DeptException("获取部门失败：" + xh, var3);
        }
    }

    @Override
    public Map<String, Object> getDeptByCode(String deptCode) throws DeptException {
        try {
            return this.deptDao.getDeptByCode(deptCode);
        } catch (Exception var3) {
            LoggerUtil.error(this.getClass(), "根据组织代码来获取组织机构异常：" + deptCode, var3);
            throw new DeptException("根据组织代码来获取组织机构异常：" + deptCode, var3);
        }
    }

    @Override
    public Map<String, Object> addDept(final Map<String, Object> dept) throws DeptException {
        String operateFlag = "1";
        boolean var11 = false;

        Map var5;
        try {
            var11 = true;
            String xh = MapUtils.getString(dept, "XH");
            if (StringUtils.isEmpty(xh)) {
                xh = Toolkit.getID();
                dept.put("XH", xh);
                String zzbh = MapUtils.getString(dept, "ZZBH");
                if (StringUtils.isEmpty(zzbh)) {
                    dept.put("ZZBH", xh);
                }
            }

            this.createBaseInfo(dept);
            dept.put("SJQX", dept.get("ORGID"));
            int count = this.deptDao.addDept(dept);
            dept.put("count", count);
            this.dataRecordService.addDataRecord("T_ADMIN_RMS_ZZJG", "powerdata.platform.dept", OperationType.ADD, "XH", xh);
            this.noticeService.notice("NOTICE_ADD", dept);
            (new Thread(new Runnable() {
                @Override
                public void run() {
                    BizLog.dataTrace("powerdata.platform.dept", MapUtils.getString(dept, "XH"), dept);
                }
            })).start();
            var5 = dept;
            var11 = false;
        } catch (Exception var12) {
            operateFlag = "0";
            LoggerUtil.error(this.getClass(), "新增部门失败：" + dept, var12);
            throw new DeptException("新增部门失败：" + dept, var12);
        } finally {
            if (var11) {
                BizOperationLogVO bizOperateLog = new BizOperationLogVO();
                bizOperateLog.setMkbs("powerdata.platform.dept");
                bizOperateLog.setCzlx("new");
                bizOperateLog.setCzzt(operateFlag);
                bizOperateLog.setDxxh(MapUtils.getString(dept, "XH"));
                bizOperateLog.setCznr("添加部门");
                bizOperateLog.setKzsj(dept);
                BizLog.operate(bizOperateLog);
            }
        }

        BizOperationLogVO bizOperateLog = new BizOperationLogVO();
        bizOperateLog.setMkbs("powerdata.platform.dept");
        bizOperateLog.setCzlx("new");
        bizOperateLog.setCzzt(operateFlag);
        bizOperateLog.setDxxh(MapUtils.getString(dept, "XH"));
        bizOperateLog.setCznr("添加部门");
        bizOperateLog.setKzsj(dept);
        BizLog.operate(bizOperateLog);
        return var5;
    }

    @Override
    public int updateDept(final Map<String, Object> zzjg) throws DeptException {
        String operateFlag = "1";
        boolean var3 = false;
        boolean var10 = false;

        int count;
        try {
            var10 = true;
            this.createBaseInfo(zzjg);
            if (StringUtils.hasText(MapUtils.getString(zzjg, "OLDZZQC"))) {
                Map<String, Object> param = new HashMap();
                param.put("ZZQC", MapUtils.getString(zzjg, "OLDZZQC") + '%');
                List<String> xhs = (List)this.deptDao.findDept(param).parallelStream().map((t) -> {
                    return MapUtils.getString(t, "XH");
                }).collect(Collectors.toList());
                this.deptDao.updateChilDeptFullName(zzjg);
                this.dataRecordService.addDataRecordBatch("T_ADMIN_RMS_ZZJG", "powerdata.platform.dept", OperationType.UPDATE, "XH", xhs);
                this.cache.reload();
            }

            count = this.deptDao.updateDept(zzjg);
            String xh = MapUtils.getString(zzjg, "XH");
            this.dataRecordService.addDataRecord("T_ADMIN_RMS_ZZJG", "powerdata.platform.dept", OperationType.UPDATE, "XH", xh);
            Map<String, Object> dept = this.deptDao.getDept(xh);
            this.noticeService.notice("NOTICE_UPDATE", dept);
            (new Thread(new Runnable() {
                @Override
                public void run() {
                    BizLog.dataTrace("powerdata.platform.dept", MapUtils.getString(zzjg, "XH"), zzjg);
                }
            })).start();
            var10 = false;
        } catch (Exception var11) {
            operateFlag = "0";
            LoggerUtil.error(this.getClass(), "更新部门失败：" + zzjg, var11);
            throw new DeptException("更新部门失败：" + zzjg, var11);
        } finally {
            if (var10) {
                BizOperationLogVO bizOperateLog = new BizOperationLogVO();
                bizOperateLog.setMkbs("powerdata.platform.dept");
                bizOperateLog.setCzlx("update");
                bizOperateLog.setCzzt(operateFlag);
                bizOperateLog.setDxxh(MapUtils.getString(zzjg, "XH"));
                bizOperateLog.setCznr("更新部门");
                bizOperateLog.setKzsj(zzjg);
                BizLog.operate(bizOperateLog);
            }
        }

        BizOperationLogVO bizOperateLog = new BizOperationLogVO();
        bizOperateLog.setMkbs("powerdata.platform.dept");
        bizOperateLog.setCzlx("update");
        bizOperateLog.setCzzt(operateFlag);
        bizOperateLog.setDxxh(MapUtils.getString(zzjg, "XH"));
        bizOperateLog.setCznr("更新部门");
        bizOperateLog.setKzsj(zzjg);
        BizLog.operate(bizOperateLog);
        return count;
    }

    @Override
    public Map<String, Object> isDelete(String deptXh) throws DeptException {
        String deleteKey = "isDelete";
        String messageKey = "message";
        Map<String, Object> result = new HashMap();
        List<Map<String, Object>> lstUsers = null;
        List lstDept = null;

        try {
            lstUsers = this.userService.getUserByDeptXh(deptXh);
            lstDept = this.getLowerDeptByXh(deptXh);
            if (CollectionUtils.isNotEmpty(lstDept)) {
                result.put(messageKey, "该部门下存在子部门,不能够删除!");
                result.put(deleteKey, false);
            } else if (CollectionUtils.isNotEmpty(lstUsers)) {
                result.put(messageKey, "该部门下存在用户,不能够删除!");
                result.put(deleteKey, false);
            } else {
                result.put(messageKey, "该部门可以删除");
                result.put(deleteKey, true);
            }
        } catch (Exception var8) {
            result.put(messageKey, "检查部门是否可以删除时出错，操作失败！");
            result.put(deleteKey, false);
            LoggerUtil.error(this.getClass(), "检查部门是否可以删除时出错，操作失败：deptXh : " + deptXh, var8);
        }

        return result;
    }


    @Override
    public List getLowerDeptByXh(String deptXh) throws DeptException {
        return this.deptDao.getLowerDeptByXh(deptXh);
    }

    @Override
    public String getErjibumenXh(String bmbh) {
        Map<String,Object> bm = deptDao.getDeptByXh(bmbh);
        String SJZZXH = MapUtils.getString(bm,"SJZZXH");
        if(StringUtils.isEmpty(SJZZXH)){
            return "ROOT";
        }else if("ROOT".equals(SJZZXH)){
            return bmbh;
        }else {
            Map<String,Object> erjibumen = deptDao.getDeptByXh(SJZZXH);
            String XH = MapUtils.getString(erjibumen,"XH");
            return XH;
        }
    }

    @Override
    public String jibie(String bmbh) {
        Map<String,Object> bm = deptDao.getDeptByXh(bmbh);
        String SJZZXH = MapUtils.getString(bm,"SJZZXH");
        if(StringUtils.isEmpty(SJZZXH)){
            return "yiji";
        }else if("ROOT".equals(SJZZXH)){
            return "erji";
        }else {
            return "sanji";
        }
    }

    @Override
    public int deleteDept(String deptXh) throws DeptException {
        try {
            Map<String, Object> param = new HashMap();
            param.put("XH", deptXh);
            param.put("SFYX", "0");
            return this.updateDept(param);
        } catch (Exception var3) {
            LoggerUtil.error(this.getClass(), "删除部门失败：deptXh : " + deptXh, var3);
            throw new DeptException("删除部门失败：deptXh : " + deptXh, var3);
        }
    }

    @Override
    public List<Map<String, Object>> findDept(Map<String, Object> params) throws DeptException {
        SQLUtils.fillLike(params, "ZZJC");
        SQLUtils.fillLike(params, "ZZQC");
        Object lstDept = null;

        try {
            lstDept = this.deptDao.findDept(params);
        } catch (Exception var4) {
            LoggerUtil.error(this.getClass(), "部门查询失败：" + params, var4);
            throw new DeptException("部门查询失败：" + params, var4);
        }

        if (CollectionUtils.isEmpty((Collection)lstDept)) {
            lstDept = new ArrayList(0);
        }

        return (List)lstDept;
    }

    @Override
    public List<Map<String, Object>> getDeptByName(Map<String, Object> param) throws DeptException {
        this.param = param;
        try {
            SQLUtils.fillLike(param, "name");
            return this.deptDao.getDeptByName(param);
        } catch (Exception var3) {
            LoggerUtil.error(this.getClass(), "通过部门名称查询部门失败 : " + param, var3);
            throw new DeptException("通过部门名称查询部门失败 : " + param, var3);
        }
    }

    @Override
    public List<DepartmentVO> getTreeData(Map<String, Object> params) throws DeptException {
        this.params = params;
        try {
            String rootXh = "ROOT";
            if (null != params.get("ROOTXH")) {
                rootXh = (String)params.get("ROOTXH");
            }

            boolean isManage = false;
            if (null != params.get("MANAGE")) {
                isManage = (Boolean)params.get("MANAGE");
            }

            List<DepartmentVO> treeData = (new DeptUtil()).getTreeData(this.cache, rootXh, isManage);
            Collections.sort(treeData, new Comparator<DepartmentVO>() {
                @Override
                public int compare(DepartmentVO dept1, DepartmentVO dept2) {
                    return dept1.getPxh() - dept2.getPxh();
                }
            });
            return treeData;
        } catch (Exception var5) {
            LoggerUtil.error(this.getClass(), "获取部门树组件数据 从缓存中读取失败 : " + params, var5);
            throw new DeptException("获取部门树组件数据 从缓存中读取失败 : " + params, var5);
        }
    }

    @Override
    public List<Map<String, Object>> findNonrootDept() throws DeptException {
        try {
            return this.deptDao.findNonrootDept();
        } catch (Exception var2) {
            LoggerUtil.error(this.getClass(), "查询非根部门", var2);
            throw new DeptException("查询非根部门", var2);
        }
    }

    @Override
    public List<Map<String, Object>> getExcelData(Map<String, Object> params) throws DeptException {
        this.params = params;
        try {
            SQLUtils.fillLike(params, "ZZJC");
            SQLUtils.fillLike(params, "ZZQC");
            return this.deptDao.findDept(params);
        } catch (Exception var3) {
            LoggerUtil.error(this.getClass(), "获取部门导出数据异常", var3);
            throw new DeptException("获取部门导出数据异常", var3);
        }
    }

    @Override
    public int addDeptList(List<Map<String, Object>> models) throws DeptException {
        String operateFlag = "1";
        boolean var12 = false;

        int var15;
        try {
            var12 = true;
            List<String> ids = new ArrayList();
            Iterator var4 = models.iterator();

            while(true) {
                if (!var4.hasNext()) {
                    this.dataRecordService.addDataRecordBatch("T_ADMIN_RMS_ZZJG", "powerdata.platform.dept", OperationType.ADD, "XH", ids);
                    this.noticeService.batchNotice("NOTICE_ADD", models);
                    var15 = models.size();
                    var12 = false;
                    break;
                }

                Map<String, Object> model = (Map)var4.next();
                String id = Toolkit.getID();
                ids.add(id);
                model.put("XH", id);
                model.put("ZZBH", id);
                this.createBaseInfo(model);
                this.deptDao.addDept(model);
            }
        } catch (Exception var13) {
            operateFlag = "0";
            LoggerUtil.error(this.getClass(), "批量新增部门信息异常", var13);
            throw new DeptException("批量新增部门信息异常", var13);
        } finally {
            if (var12) {
                BizOperationLogVO bizOperateLog = new BizOperationLogVO();
                bizOperateLog.setMkbs("powerdata.platform.dept");
                bizOperateLog.setCzlx("new");
                bizOperateLog.setCzzt(operateFlag);
                bizOperateLog.setCznr("批量添加部门");
                HashMap depts = new HashMap();
                depts.put("depts", models);
                bizOperateLog.setKzsj(depts);
                BizLog.operate(bizOperateLog);
            }
        }

        BizOperationLogVO bizOperateLog = new BizOperationLogVO();
        bizOperateLog.setMkbs("powerdata.platform.dept");
        bizOperateLog.setCzlx("new");
        bizOperateLog.setCzzt(operateFlag);
        bizOperateLog.setCznr("批量添加部门");
        Map<String, Object> depts = new HashMap();
        depts.put("depts", models);
        bizOperateLog.setKzsj(depts);
        BizLog.operate(bizOperateLog);
        return var15;
    }

    @Override
    public int isCanSetInvalid(String deptXh) throws DeptException {
        try {
            List<Map<String, Object>> deptList = this.getAllDept();
            Iterator var3 = deptList.iterator();

            Map dept;
            do {
                if (!var3.hasNext()) {
                    List<Map<String, Object>> userList = this.userService.getAllUser();
                    Iterator var8 = userList.iterator();

                    Map user;
                    do {
                        if (!var8.hasNext()) {
                            return 1;
                        }

                        user = (Map)var8.next();
                    } while(!deptXh.equals(MapUtils.getString(user, "BMBH")) || !"1".equals(MapUtils.getString(user, "SFYX")));

                    return 3;
                }

                dept = (Map)var3.next();
            } while(!deptXh.equals(MapUtils.getString(dept, "SJZZXH")) || !"1".equals(MapUtils.getString(dept, "SFYX")));

            return 2;
        } catch (Exception var6) {
            LoggerUtil.error(DeptServiceImpl.class, "检查部门是否能由有效改为无效状态, deptXh : {}", new Object[]{deptXh, var6});
            throw new DeptException("检查部门是否能由有效改为无效状态, deptXh : " + deptXh, var6);
        }
    }
}